<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Description of RecordNotExists
 *
 * @author chaporgin_a
 */
class VA_Form_Validator_RecordNotExists extends VA_Form_Validator {
  public function init($options) {
    parent::init($options);
    $this->getOption('table');
    $this->getOption('field');
    $this->setInitOptionIfNone('url', '/index.php?option=com_electroforms&task=validate&name=a9986');
  }
  /**
   * Используется чтобы вернуть записи с заданным критерием
   * @return array
   */
  protected function askDatabase($value){
    $db = JFactory::getDBO();
    $table = $this->getOption('table');
    $field = $this->getOption('field');
    $query = sprintf('SELECT COUNT(*) FROM %s WHERE %s=%s'
            , $this->getOption('table')
            , $this->getOption('field')
            , $db->Quote($value)
            );
    $db->setQuery($query);
    $db->query();
    $res = $db->loadResultArray();
    return $res;
  }
  public function isValid($value) {
    $res = $this->askDatabase($value);
    if((count($res) == 0) || ($res[0] > 0)) {
      $this->errorMessages[] = 'Уже существует!';
      return FALSE;
    }
    return TRUE;
  }

  public function getHTMLTagAttributes() {
//    $remote = '{url: /check.php}';
    return array(
      'remote' => array(JRoute::_( $this->getOption('url'), FALSE))
      //'class' => array(sprintf('{validate: {remote: "%s"}}', $this->getOption('url')))
    );
  }
}

